package org.jeecg.modules.clockRecord.controller;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.classes.entity.Classes;
import org.jeecg.modules.classes.service.IClassesService;
import org.jeecg.modules.clockRecord.entity.ClockRecord;
import org.jeecg.modules.clockRecord.service.IClockRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.employee.entity.Employee;
import org.jeecg.modules.employee.service.IEmployeeService;
import org.jeecg.modules.identificationRecord.entity.IdentificationRecord;
import org.jeecg.modules.identificationRecord.service.IIdentificationRecordService;
import org.jeecg.modules.scheduling.entity.CardVO;
import org.jeecg.modules.scheduling.entity.Scheduling;
import org.jeecg.modules.scheduling.entity.SchedulingBaseInfoDTO;
import org.jeecg.modules.scheduling.entity.SchedulingVO;
import org.jeecg.modules.scheduling.service.ISchedulingService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 打卡记录
 * @Author: jeecg-boot
 * @Date:   2025-01-26
 * @Version: V1.0
 */
@Api(tags="打卡记录")
@RestController
@RequestMapping("/clockRecord/clockRecord")
@Slf4j
public class ClockRecordController extends JeecgController<ClockRecord, IClockRecordService> {
	@Autowired
	private IClockRecordService clockRecordService;
	 @Autowired
	 private ISchedulingService schedulingService;
	 @Autowired
	 private IEmployeeService employeeService;
	 @Autowired
	 private IClassesService classesService;
	 @Autowired
	 private ISysDictService dictService;
	 @Autowired
	 private ISysDepartService departService;
	 @Autowired
	 private IIdentificationRecordService identificationRecordService;

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;

	/**
	 * 分页列表查询
	 *
	 * @param clockRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="打卡记录-分页列表查询", notes="打卡记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ClockRecord clockRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Map<String, String[]> parameterMap = req.getParameterMap();
		String beginTime = null, endTime = null;
		String[] begin = parameterMap.get("time_begin");
		String[] end = parameterMap.get("time_end");
		if (begin != null && begin.length > 0){
			beginTime = begin[0];
		}
		if (end != null && end.length > 0){
			endTime = end[0];
		}
		String dept = clockRecord.getDept();
		QueryWrapper<ClockRecord> queryWrapper = QueryGenerator.initQueryWrapper(clockRecord, req.getParameterMap());
		if (!StringUtils.isEmpty(dept)) {
			queryWrapper.eq("dept", dept).or(w -> w.eq("classes", dept));
			clockRecord.setDept(null);
		}
		if (!StringUtils.isEmpty(beginTime)){
			queryWrapper.ge("STR_TO_DATE(CONCAT(LEFT(date, 10), ' ', in_time), '%Y-%m-%d %H:%i:%s')", beginTime);
		}
		if (!StringUtils.isEmpty(endTime)){
			queryWrapper.le("STR_TO_DATE(CONCAT(LEFT(date, 10), ' ', in_time), '%Y-%m-%d %H:%i:%s')", endTime);
		}
		Page<ClockRecord> page = new Page<ClockRecord>(pageNo, pageSize);
		IPage<ClockRecord> pageList = clockRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @ApiOperation(value="打卡记录-分页列表查询", notes="打卡记录-分页列表查询")
	 @GetMapping(value = "/abnormalList")
	 public Result<?> abnormalList(ClockRecord clockRecord,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 String dept = clockRecord.getDept();
		 QueryWrapper<ClockRecord> queryWrapper = QueryGenerator.initQueryWrapper(clockRecord, req.getParameterMap());
		 if (!StringUtils.isEmpty(dept)) {
			 queryWrapper.eq("dept", dept).or(w -> w.eq("classes", dept));
			 clockRecord.setDept(null);
		 }
		 queryWrapper.eq("abnormal", 1);
		 if (!hasNowExceededHour(17)){//17点之前
			 // 关键修改：排除今天且 classes_type=2 的记录
			 queryWrapper.not(wrapper ->
					 wrapper.eq("DATE(date)", DateUtils.formatDate())
							 .eq("classes_type", 2)
			 );
		 }
		 Page<ClockRecord> page = new Page<ClockRecord>(pageNo, pageSize);
		 IPage<ClockRecord> pageList = clockRecordService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @ApiOperation(value="打卡记录-获取个人每月日历信息", notes="打卡记录-获取个人每月日历信息")
	 @GetMapping(value = "/getPersonInfo")
	 public Result<?> getPersonInfo(@RequestParam(name = "admitGuid") String admitGuid,
									@RequestParam(name = "monthStart") String monthStart,
									@RequestParam(name = "nextMonthStart") String nextMonthStart) {
		 List<Map<String, Object>> list = clockRecordService.getPersonInfo(admitGuid, monthStart, nextMonthStart);
		 return Result.OK(list);
	 }

	 @ApiOperation(value="大屏-echarts左1", notes="大屏-echarts左1")
	 @GetMapping(value = "/m/getLeft1")
	 public Result<?> getLeft1(@RequestParam(name = "start") String start,
							   @RequestParam(name = "end") String end) {
		 List<Map<String, Object>> left1 = clockRecordService.getLeft1(start, end);
		 return Result.OK(left1);
	 }

	 @ApiOperation(value="大屏-echarts左2", notes="大屏-echarts左2")
	 @GetMapping(value = "/m/getLeft2")
	 public Result<?> getLeft2(@RequestParam(name = "start") String start,
							   @RequestParam(name = "end") String end) {
		 List<Map<String, Object>> left2 = clockRecordService.getLeft2(start, end);
		 return Result.OK(left2);
	 }

	 @ApiOperation(value="大屏-echarts中3", notes="大屏-echarts中3")
	 @GetMapping(value = "/m/getCenter3")
	 public Result<?> getCenter3() {
		 List<Map<String, Object>> center3 = clockRecordService.getCenter3();
		 return Result.OK(center3);
	 }

	 @ApiOperation(value="大屏-右侧列表", notes="大屏-右侧列表")
	 @GetMapping(value = "/m/getRight")
	 public Result<?> getRight(@RequestParam(name = "start") String start,
							   @RequestParam(name = "end") String end) {
		 List<DictModel> solveReason = dictService.queryDictItemsByCode("solve_reason");
		 Map<String, String> dictMap = solveReason.stream()
				 .collect(Collectors.toMap(DictModel::getValue, DictModel::getText));

		 Set<Integer> travelSet = new HashSet<>(Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21));
		 Set<Integer> leaveSet = new HashSet<>(Arrays.asList(4, 6, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21));
		 Set<Integer> otherSet = new HashSet<>(Arrays.asList(1, 10));

		 QueryWrapper<ClockRecord> wrapper = new QueryWrapper<>();
		 if (hasNowExceededHour(17)){//17点之后
			 wrapper.eq("DATE(date)", DateUtils.formatDate());
		 } else {//17点之前
			 wrapper.and(w -> w
					 .apply("DATE(date) = CURDATE()")      // 条件1
					 .in("classes_type", 1, 3)             // 条件2
			 )
					 .or(w -> w
							 .apply("DATE(date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")  // 条件3
							 .eq("classes_type", 2)                // 条件4
					 );
		 }
//		 wrapper.between("date", start, end);
		 wrapper.eq("solve", 1);

		 List<Map<String, Object>> maps = clockRecordService.listMaps(wrapper);

		 Map<String, List<Map<String, Object>>> categorizedMaps = new HashMap<>();
		 categorizedMaps.put("travel", new ArrayList<>());
		 categorizedMaps.put("leaves", new ArrayList<>());
		 categorizedMaps.put("other", new ArrayList<>());

		 for (Map<String, Object> map : maps) {
			 Object solveReasonObj = map.get("solve_reason");
			 if (solveReasonObj == null) {
				 continue;
			 }
			 try {
				 int solveReasonInt = Integer.parseInt(solveReasonObj.toString());
				 if (travelSet.contains(solveReasonInt)) {
					 addDictInfo(map, dictMap.get(String.valueOf(solveReasonInt)));
					 categorizedMaps.get("travel").add(map);
				 } else if (leaveSet.contains(solveReasonInt)) {
					 addDictInfo(map, dictMap.get(String.valueOf(solveReasonInt)));
					 categorizedMaps.get("leaves").add(map);
				 } else if (otherSet.contains(solveReasonInt)) {
					 addDictInfo(map, dictMap.get(String.valueOf(solveReasonInt)));
					 categorizedMaps.get("other").add(map);
				 }
			 } catch (NumberFormatException e) {
				 System.err.println("无法解析 solve_reason: " + solveReasonObj);
			 }
		 }

		 return Result.OK(categorizedMaps);
	 }

	 private void addDictInfo(Map<String, Object> map, String dictText) {
		 map.put("dict", dictText);
	 }

//	 @AutoLog(value = "打卡记录-大屏-表格")
//	 @ApiOperation(value="打卡记录-大屏-表格", notes="打卡记录-大屏-表格")
//	 @GetMapping(value = "/today")
//	 public Result<?> today() {
//		 List<ClockRecord> clockRecords = clockRecordService.getTodayAttendance();
//		 Map<String, SchedulingVO> groupedByDept = clockRecords.stream()
//				 .collect(Collectors.groupingBy(
//						 baseInfo -> Optional.ofNullable(baseInfo.getDept()).orElse("未知"), // 使用默认值替代null
//						 Collectors.collectingAndThen(
//								 Collectors.mapping(this::createOrUpdateSchedulingVO, Collectors.toList()),
//								 list -> list.stream().reduce(new SchedulingVO(), this::mergeSchedulingVOs)
//						 )
//				 ));
//		 ArrayList<SchedulingVO> schedulingVOS = new ArrayList<>(groupedByDept.values());
//		 LambdaQueryWrapper<SysDepart> wrapper = Wrappers.lambdaQuery();
//		 wrapper.orderByAsc(SysDepart::getDepartOrder);
//		 List<SysDepart> list = departService.list(wrapper);
//		 // 创建部门优先级Map
//		 Map<String, Integer> deptPriority = new HashMap<>();
//		 Map<String, String> deptNameId = new HashMap<>();
//		 for (int i = 0; i < list.size(); i++) {
//			 deptPriority.put(list.get(i).getDepartName(), i);
//			 deptNameId.put(list.get(i).getDepartName(), list.get(i).getId());
//		 }
//		 // 排序
//		 schedulingVOS.sort(Comparator.comparingInt(s -> deptPriority.get(s.getDept())));
//		 LambdaQueryWrapper<Employee> employeeWrapper = Wrappers.lambdaQuery();
//		 employeeWrapper.eq(Employee::getDisable, 0);
//		 List<Employee> list1 = employeeService.list(employeeWrapper);
//		 // 预先统计每个部门的在职人数（按部门ID分组）
//		 Map<String, Long> deptEmployeeCount = list1.stream()
//				 .collect(Collectors.groupingBy(
//						 Employee::getDept, // 假设 Employee.dept 是部门ID
//						 Collectors.counting()
//				 ));
//		 // 在设置 SchedulingVO 的 number 时直接查询 Map
//		 List<SchedulingVO> result = schedulingVOS.stream()
//				 .peek(s -> {
//					 String deptId = deptNameId.get(s.getDept());
//					 if (deptId != null) {
//						 s.setNumber(deptEmployeeCount.getOrDefault(deptId, 0L).intValue());
//					 } else {
//						 // 部门名称不存在于 SysDepart，可能需要特殊处理
//						 s.setNumber(0);
//					 }
//				 })
//				 .collect(Collectors.toList());
//		 return Result.OK(result);
//	 }

	 @ApiOperation(value="大屏-表格", notes="大屏-表格")
	 @PostMapping(value = "/m/today")
	 public Result<?> today(@RequestBody List<SchedulingVO> schedulingVOS) {
		 List<ClockRecord> clockRecords = clockRecordService.getTodayAttendance();
		 List<Classes> list = classesService.list();
		 List<Employee> employeeList = employeeService.deptNameList();
		 Map<String, Classes> collect = list.stream().collect(Collectors.toMap(Classes::getId, c -> c));

		 // 预构建部门索引和课程索引
		 Map<String, List<ClockRecord>> deptMap = clockRecords.stream()
				 .collect(Collectors.groupingBy(ClockRecord::getDept));
		 Map<String, List<ClockRecord>> classesMap = clockRecords.stream()
				 .filter(r -> !StringUtils.isEmpty(r.getClasses()))
				 .collect(Collectors.groupingBy(ClockRecord::getClasses));

		 for(SchedulingVO schedulingVO : schedulingVOS){
			 List<String> classes = schedulingVO.getClasses();
			 String currentDept = schedulingVO.getDept();

			 if (classes.isEmpty()) {
				 processDeptGroup(schedulingVO, deptMap.get(currentDept), collect);
				 int count = (int) employeeList.stream().filter(e -> currentDept.equals(e.getDept())).count();
				 schedulingVO.getNumber().set(0, count);
			 } else {
				 processClassesGroup(schedulingVO, classes, classesMap, collect, employeeList);
			 }
		 }

		 return Result.OK(schedulingVOS);
	 }

	 /**
	  * 处理部门分组
	  * @param vo
	  * @param records
	  * @param collect
	  */
	 private void processDeptGroup(SchedulingVO vo, List<ClockRecord> records,
								   Map<String, Classes> collect) {
		 if (records == null) return;

		 for (ClockRecord record : records) {
			 Classes classes = collect.get(record.getClassesId());
			 if (!StringUtils.isEmpty(record.getInTime())){
				 addToTimeSlot(vo.getDay().get(0), vo.getNight().get(0), record, classes);
			 } else if (record.getSolveReason() != null && 11 == record.getSolveReason()) {
				 vo.getLeave().get(0).add(CardVO.fromClockRecord(record, classes));
			 } else {
				 String startTime = classes.getStartTime();
				 String s = DateUtils.formatDate("HH:mm:ss");
				 if ((hasNowExceededHour(17) && s.compareTo(startTime) > 0)
						 || (!hasNowExceededHour(17) && (classes.getClassesType() == 2 || s.compareTo(startTime) > 0))) {
					 vo.getAbsence().get(0).add(CardVO.fromClockRecord(record, classes));
				 }
//				 if (s.compareTo(startTime) > 0) {
//					 vo.getAbsence().get(0).add(CardVO.fromClockRecord(record, classes));
//				 }
			 }
		 }
	 }

	 /**
	  * 处理班次分组
	  * @param vo
	  * @param classes
	  * @param classesMap
	  * @param collect
	  * @param employeeList
	  */
	 private void processClassesGroup(SchedulingVO vo, List<String> classes, Map<String,
			 List<ClockRecord>> classesMap, Map<String, Classes> collect, List<Employee> employeeList) {
		 for (int i = 0; i < classes.size(); i++) {
			 String className = classes.get(i);
			 List<ClockRecord> matchedRecords;

			 // 处理空课程名的特殊逻辑
			 if (StringUtils.isEmpty(className)) {
				 matchedRecords = classesMap.values().stream()
						 .flatMap(List::stream)
						 .filter(r -> vo.getDept().equals(r.getDept()) && !classes.contains(r.getClasses()))
						 .collect(Collectors.toList());
				 int count = (int) employeeList.stream().filter(e -> vo.getDept().equals(e.getDept()) && !classes.contains(e.getClasses())).count();
				 vo.getNumber().set(i, count);
			 } else {
				 matchedRecords = classesMap.getOrDefault(className, Collections.emptyList());
				 int count = (int) employeeList.stream().filter(e -> className.equals(e.getClasses())).count();
				 vo.getNumber().set(i, count);
			 }

			 // 确保索引有效性
			 ensureIndex(vo.getDay(), i);
			 ensureIndex(vo.getNight(), i);

			 for (ClockRecord record : matchedRecords) {
				 Classes classes1 = collect.get(record.getClassesId());
				 if (!StringUtils.isEmpty(record.getInTime())){
					 addToTimeSlot(vo.getDay().get(i), vo.getNight().get(i), record, classes1);
				 } else if (record.getSolveReason() != null && 11 == record.getSolveReason()) {
					 vo.getLeave().get(i).add(CardVO.fromClockRecord(record, classes1));
				 } else {
					 String startTime = classes1.getStartTime();
					 String s = DateUtils.formatDate("HH:mm:ss");
					 if ((hasNowExceededHour(17) && s.compareTo(startTime) > 0)
							 || (!hasNowExceededHour(17) && (classes1.getClassesType() == 2 || s.compareTo(startTime) > 0))) {
						 vo.getAbsence().get(i).add(CardVO.fromClockRecord(record, classes1));
					 }
//					 if (s.compareTo(startTime) > 0) {
//                         vo.getAbsence().get(i).add(CardVO.fromClockRecord(record, classes1));
//                     }
				 }
			 }
		 }
	 }

	 /**
	  * 确保索引有效
	  *
	  * @param timeSlots 时间槽列表
	  * @param index     索引
	  */
	 private void ensureIndex(List<List<CardVO>> timeSlots, int index) {
		 while (timeSlots.size() <= index) {
			 timeSlots.add(new ArrayList<>());
		 }
	 }

	 /**
	  * 添加打卡记录到对应的时间槽
	  *
	  * @param dayList   白天时间槽
	  * @param nightList 夜晚时间槽
	  * @param record    打卡记录
	  * @param classes   课程信息
	  */
	 private void addToTimeSlot(List<CardVO> dayList, List<CardVO> nightList,
								ClockRecord record, Classes classes) {
		 if (record.getClassesType() == 1 || record.getClassesType() == 3) {
			 dayList.add(CardVO.fromClockRecord(record, classes));
		 } else {
			 nightList.add(CardVO.fromClockRecord(record, classes));
		 }
	 }

	 @ApiOperation(value="打卡记录-大屏-人数", notes="打卡记录-大屏-人数")
	 @GetMapping(value = "/m/total")
	 public Result<?> total() {
		LambdaQueryWrapper<Employee> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(Employee::getDisable, 0);
		 int count = employeeService.count(wrapper);
		 List<ClockRecord> clockRecords = clockRecordService.getToday();
		 Map<String, Integer> map = new HashMap<>();
		 map.put("total", count);//在职人数
		 int actualCount = (int) clockRecords.stream()
				 .filter(record -> record.getInTime() != null)
				 .count();
		 map.put("actual", actualCount);//实际出勤人数
//		 map.put("notClock", clockRecords.size() - actualCount);//未打卡人数
		 int lateCount = (int) clockRecords.stream()
				 .filter(record -> record.getSolveReason()!=null && record.getSolveReason() == 1)
				 .count();
		 map.put("late", lateCount);//迟到人数
		 int absenceCount = (int) clockRecords.stream()
				 .filter(record -> record.getSolveReason()!=null && Arrays.asList(2, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21).contains(record.getSolveReason()))
				 .count();
		 map.put("absence", absenceCount);//缺勤人数
		 return Result.OK(map);
	 }

	 @AutoLog(value = "打卡记录-处理异常")
	 @ApiOperation(value="打卡记录-处理异常", notes="打卡记录-处理异常")
	 @PostMapping(value = "/solve")
	 public Result<?> solve(@RequestBody ClockRecord clockRecord) {
		 clockRecordService.updateById(clockRecord);
		 return Result.OK("添加成功！");
	 }

	 @AutoLog(value = "打卡记录-删除最晚打卡时间")
	 @ApiOperation(value="打卡记录-删除最晚打卡时间", notes="打卡记录-删除最晚打卡时间")
	 @PostMapping(value = "/deleteOutTime")
	 public Result<?> deleteOutTime(@RequestParam(name = "id") String id) {
		 ClockRecord byId = clockRecordService.getById(id);
		 if (byId == null) {
			 return Result.error("未找到对应数据");
		 }
		 LambdaUpdateWrapper<ClockRecord> wrapper = Wrappers.lambdaUpdate();
		 wrapper.eq(ClockRecord::getId, byId.getId());
		 wrapper.set(ClockRecord::getOutTime, null);
		 clockRecordService.update(wrapper);
		 return Result.OK("删除成功！");
	 }

	 @AutoLog(value = "打卡记录-上班时间更换为下班时间")
	 @ApiOperation(value="打卡记录-上班时间更换为下班时间", notes="打卡记录-上班时间更换为下班时间")
	 @PostMapping(value = "/inTimeToOutTime")
	 public Result<?> inTimeToOutTime(@RequestParam(name = "id") String id) {
		 ClockRecord byId = clockRecordService.getById(id);
		 if (byId == null) {
			 return Result.error("未找到对应数据");
		 }
		 LambdaUpdateWrapper<ClockRecord> wrapper = Wrappers.lambdaUpdate();
		 wrapper.eq(ClockRecord::getId, byId.getId());
		 wrapper.set(ClockRecord::getOutTime, byId.getInTime());
		 wrapper.set(ClockRecord::getInTime, null);
		 clockRecordService.update(wrapper);
		 return Result.OK("更换成功！");
	 }
	
	/**
	 *   添加
	 *
	 * @param clockRecord
	 * @return
	 */
	@AutoLog(value = "打卡记录-添加")
	@ApiOperation(value="打卡记录-添加", notes="打卡记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ClockRecord clockRecord) {
		clockRecordService.save(clockRecord);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param clockRecord
	 * @return
	 */
	@AutoLog(value = "打卡记录-编辑")
	@ApiOperation(value="打卡记录-编辑", notes="打卡记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ClockRecord clockRecord) {
		clockRecordService.updateById(clockRecord);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "打卡记录-通过id删除")
	@ApiOperation(value="打卡记录-通过id删除", notes="打卡记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		clockRecordService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "打卡记录-批量删除")
	@ApiOperation(value="打卡记录-批量删除", notes="打卡记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.clockRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="打卡记录-通过id查询", notes="打卡记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ClockRecord clockRecord = clockRecordService.getById(id);
		if(clockRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(clockRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param clockRecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ClockRecord clockRecord) {
		Map<String, String[]> parameterMap = request.getParameterMap();
		String beginTime = null, endTime = null;
		String[] begin = parameterMap.get("time_begin");
		String[] end = parameterMap.get("time_end");
		if (begin != null && begin.length > 0){
			beginTime = begin[0];
		}
		if (end != null && end.length > 0){
			endTime = end[0];
		}
		// Step.1 组装查询条件
		String dept = clockRecord.getDept();
		QueryWrapper<ClockRecord> queryWrapper = QueryGenerator.initQueryWrapper(clockRecord, request.getParameterMap());
		if (!StringUtils.isEmpty(beginTime)){
			queryWrapper.ge("STR_TO_DATE(CONCAT(LEFT(date, 10), ' ', in_time), '%Y-%m-%d %H:%i:%s')", beginTime);
		}
		if (!StringUtils.isEmpty(endTime)){
			queryWrapper.le("STR_TO_DATE(CONCAT(LEFT(date, 10), ' ', in_time), '%Y-%m-%d %H:%i:%s')", endTime);
		}
		if (!StringUtils.isEmpty(dept)) {
			queryWrapper.eq("dept", dept).or(w -> w.eq("classes", dept));
			clockRecord.setDept(null);
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<ClockRecord> pageList = clockRecordService.list(queryWrapper);
		List<ClockRecord> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "打卡记录"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, ClockRecord.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams  exportParams=new ExportParams("打卡记录报表", "导出人:" + sysUser.getRealname(), "打卡记录");
		exportParams.setImageBasePath(upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
    }

	 private String getId(ClockRecord item) {
		 try {
			 return PropertyUtils.getProperty(item, "id").toString();
		 } catch (Exception e) {
			 e.printStackTrace();
			 return null;
		 }
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ClockRecord> list = ExcelImportUtil.importExcel(file.getInputStream(), ClockRecord.class, params);
				Map<String, ClockRecord> map = list.stream().filter(c -> c.getWorkNumber() != null).collect(Collectors.toMap(ClockRecord::getWorkNumber, record -> record));
//				long start = System.currentTimeMillis();
//				clockRecordService.saveBatch(list);
//				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				QueryWrapper<ClockRecord> wrapper = new QueryWrapper<>();
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, -1);
				wrapper.eq("date(date)", DateUtils.formatDate(calendar));
//				wrapper.eq("date(date)", "2025-02-21");
				List<ClockRecord> today = clockRecordService.list(wrapper);
				List<ClockRecord> updateList = today.stream().peek(clockRecord -> {
					String workNumber = clockRecord.getWorkNumber();
					ClockRecord clockRecord1 = map.get(workNumber);
					if (clockRecord1==null) {
						log.info("未找到对应数据: {}", workNumber);
						clockRecord.setAbnormal(1);
						clockRecord.setAbnormalType(2);
					} else {
						if(!StringUtils.isEmpty(clockRecord1.getInTime())){
							clockRecord.setInTime(clockRecord1.getInTime());
							clockRecord.setAbnormal(0);
							clockRecord.setAbnormalType(1);
						}
						clockRecord.setOutTime(clockRecord1.getOutTime());
					}
				}).collect(Collectors.toList());
				clockRecordService.updateBatchById(updateList);
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

//	 private SchedulingVO createOrUpdateSchedulingVO(ClockRecord baseInfo) {
//		 SchedulingVO schedulingVO = new SchedulingVO()
//				 .setDept(baseInfo.getDept());
//
//		 CardVO cardVO = new CardVO()
//				 .setName(baseInfo.getAdmitName()).setAbnormalType(baseInfo.getAbnormalType())
//				 .setFaceUrl(baseInfo.getFaceUrl()).setOutTime(baseInfo.getOutTime())
//				 .setAdmitGuid(baseInfo.getAdmitGuid()).setInTime(baseInfo.getInTime())
//				 .setWorkNumber(baseInfo.getWorkNumber()).setSolve(baseInfo.getSolve())
//				 .setAbnormal(baseInfo.getAbnormal());
//
//		 if (baseInfo.getClassesType() == 1 || baseInfo.getClassesType()==3) { // 白班
//			 if (schedulingVO.getDay() == null) {
//				 schedulingVO.setDay(new ArrayList<>());
//			 }
//			 schedulingVO.getDay().add(cardVO);
//		 } else if (baseInfo.getClassesType() == 2) { // 夜班
//			 if (schedulingVO.getNight() == null) {
//				 schedulingVO.setNight(new ArrayList<>());
//			 }
//			 schedulingVO.getNight().add(cardVO);
//		 }
//
//		 return schedulingVO;
//	 }

	 private SchedulingVO mergeSchedulingVOs(SchedulingVO existing, SchedulingVO newOne) {
		 if (existing.getDept() == null) {
			 existing.setDept(newOne.getDept());
		 }

		 if (newOne.getDay() != null) {
			 if (existing.getDay() == null) {
				 existing.setDay(new ArrayList<>());
			 }
			 existing.getDay().addAll(newOne.getDay());
		 }

		 if (newOne.getNight() != null) {
			 if (existing.getNight() == null) {
				 existing.setNight(new ArrayList<>());
			 }
			 existing.getNight().addAll(newOne.getNight());
		 }

		 return existing;
	 }

	 @AutoLog(value = "打卡记录-测试")
	 @ApiOperation(value="打卡记录-测试", notes="打卡记录-测试")
	 @PostMapping(value = "/test")
	 public Result<?> test() {
		 LambdaQueryWrapper<ClockRecord> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(ClockRecord::getDate, "2025-06-06 00:00:00");
		 wrapper.eq(ClockRecord::getClassesType, 2);
		 List<ClockRecord> list = clockRecordService.list(wrapper);
		 for (ClockRecord clockRecord : list) {
			 String admitGuid = clockRecord.getAdmitGuid();
			 QueryWrapper<IdentificationRecord> wrapper1 = new QueryWrapper<>();
			 wrapper1.eq("admit_guid", admitGuid);
			 wrapper1.eq("DATE(create_time)", "2025-06-07");
//			 wrapper1.orderByDesc("create_time");
			 wrapper1.last("limit 1");
			 IdentificationRecord one = identificationRecordService.getOne(wrapper1);
//			 IdentificationRecord todayLastByAdmitGuid = identificationRecordService.getTodayLastByAdmitGuid(admitGuid);
			 if (one != null) {
				 clockRecord.setOutDate(DateUtils.formatDate(one.getTime(), "yyyy-MM-dd"));
				 clockRecord.setOutTime(DateUtils.formatDate(one.getTime(), "HH:mm:ss"));
			 }
		 }
		 clockRecordService.updateBatchById(list);
		 return Result.OK();
	 }

	 public boolean hasNowExceededHour(int hour){
		 // 获取当前系统时间
		 LocalTime currentTime = LocalTime.now();
		 // 定义中午12点的时间
		 LocalTime noonTime = LocalTime.of(hour, 0);
		 // 判断当前时间是否大于12点
		 return currentTime.isAfter(noonTime);
	 }

}
